package org.example.Monotone_stack;

import java.util.Arrays;
import java.util.LinkedList;

public class Catch_rainwater {
    public static void main(String[] args) {
        //接雨水

        //给定 n 个非负整数表示每个宽度为 1 的柱子的高度图，计算按此排列的柱子，下雨之后能接多少雨水。
        int[] height = {4,2,0,3,2,5};
        int trap = trap(height);
        System.out.println(trap);
    }

    //单调栈3ms
    public static int trap(int[] height) {
        int res = 0;
        LinkedList<Integer> linkedList = new LinkedList<>();
        linkedList.add(0);
        for (int i = 1; i < height.length; i++) {
            if (height[i] < height[linkedList.getLast()]){
                linkedList.add(i);
            }else if (height[i] == height[linkedList.getLast()]){
                linkedList.removeLast();
                linkedList.add(i);
            } else if (height[i] > height[linkedList.getLast()]) {
                while(!linkedList.isEmpty() && height[i] > height[linkedList.getLast()]) {
                    Integer bottom = linkedList.removeLast();
                    if (!linkedList.isEmpty()) {
                        int h = Math.min(height[linkedList.getLast()], height[i]) - height[bottom];
                        int w = i - linkedList.getLast() - 1;
                        res += h * w;
                    }
                }
                linkedList.add(i);
            }
        }
        return res;
    }
    //双指针暴力解超时
    public static int trap2(int[] height) {
        int res = 0;
        int pre = 0;
        int last = height.length-1;
        while(pre < last){
            if (height[pre] != 0 && height[last] != 0){
                for (int i = pre; i <= last; i++) {
                    if (height[i] > 0){
                        height[i]--;
                    }else {
                        res++;
                    }
                }
                System.out.println(Arrays.toString(height));
                System.out.println(res);
            }
            if (height[pre] == 0) pre++;
            if (height[last] == 0) last--;
        }
        return res;
    }
}
